﻿using UnityEngine;
using System.Collections;

public class EnemyAttack : MonoBehaviour 
{
	int damage = 1;
	float timeBetweenAttacks = 1f;
	PlayerHealth playerHealth;
	GameObject player;
	bool playerInRange;
    float timer;
	int triggers = 0;

	// Use this for initialization
	void Start () 
	{
		player = GameObject.Find ("Player");
        if (player == null)
        {
            Debug.Log ("Det går galt i starten");
        }
		playerHealth = player.GetComponent<PlayerHealth>();
	}
	
	// Update is called once per frame
	void Update () 
	{
        timer += Time.deltaTime;
		if (triggers > 1 && timer >= timeBetweenAttacks && playerHealth.hp > 0) 
		{
            Attack ();
		}
        if (playerHealth.hp <= 0)
        {
			triggers = 0;
        }
	
	}

	void OnTriggerEnter2D(Collider2D other)
	{
		if (other.gameObject == player) 
		{
			triggers++;
            Debug.Log ("Player in range");
		}
	}

    void OnTriggerExit2D(Collider2D other)
    {
        if (other.gameObject == player)
        {
			triggers--;
            Debug.Log("Player out of Range");
        }
    }

	void Attack()
	{
        timer = 0f;
		playerHealth.TakeDamage (damage);
	}
}
